<!-- 操作日志 -->
<template>
  <div class="operation-logs">
    <!-- 筛选栏 -->
    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <label>关键词</label>
          <input type="text" placeholder="请输入关键词" v-model="query.keyword" @keyup.enter="onSearch">
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="onSearch">搜索</button>
        <button class="btn-secondary" @click="onReset">重置</button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th style="width:32px"><input type="checkbox" v-model="selectAll" @change="toggleSelectAll"></th>
            <th>日志编号</th>
            <th>员工账号</th>
            <th>操作模块</th>
            <th>操作内容</th>
            <th>操作时间</th>
            <th style="width:80px">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, idx) in tableData" :key="idx">
            <td><input type="checkbox" v-model="row.selected" @change="updateSelectAll"></td>
            <td class="link-style">{{ row.logNo || row.id }}</td>
            <td>{{ row.account }}</td>
            <td>{{ row.module }}</td>
            <td>{{ row.content }}</td>
            <td>{{ row.time }}</td>
            <td class="link-style" @click="deleteLog(row)">删除</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
        <label>全选</label>
        <button class="btn-secondary" @click="exportLogs">导出</button>
      </div>
      <div class="pagination">
        <button @click="prevPage">&lt;</button>
        <button v-for="page in totalPages" :key="page" :class="{ active: currentPage === page }" @click="goToPage(page)">{{ page }}</button>
        <button @click="nextPage">&gt;</button>
        <select v-model="pageSize" @change="onPageSizeChange">
          <option :value="5">5条/页</option>
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
        </select>
      </div>
    </div>
  </div>
</template>

<script>
import { pageOperationLogs, deleteOperationLog, batchDeleteOperationLogs } from '@/api/logs'
import * as XLSX from 'xlsx'

export default {
  name: 'OperationLogs',
  data() {
    return {
      selectAll: false,
      currentPage: 1,
      pageSize: 5,
      totalPages: 1,
      total: 0,
      tableData: [],
      loading: false,
      query: {
        keyword: ''
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const params = {
          current: this.currentPage,
          size: this.pageSize,
          keyword: this.query.keyword || undefined
        }
        const res = await pageOperationLogs(params)
        const payload = res?.data
        // 兼容多种分页返回格式
        const data = payload?.data || payload || {}
        const records = data.records || data.list || []
        this.total = Number(data.total || 0)
        this.totalPages = Math.max(1, Math.ceil(this.total / this.pageSize))
        this.tableData = records.map(item => ({
          selected: false,
          id: item.id,
          logNo: item.logNo,
          account: item.employeeAccount,
          name: item.operator || '-',
          module: item.operationModule,
          content: item.operationContent,
          ip: item.loginIp || '-',
          time: this.formatTime(item.operationTime),
          uid: item.uid
        }))
        this.updateSelectAll()
      } catch (error) {
        console.error('获取操作日志失败:', error)
      } finally {
        this.loading = false
      }
    },
    formatTime(timeStr) {
      if (!timeStr) return '-'
      try {
        const date = new Date(timeStr)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } catch {
        return timeStr
      }
    },
    onSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    onReset() {
      this.query.keyword = ''
      this.currentPage = 1
      this.fetchData()
    },
    async deleteLog(row) {
      if (!confirm('确定要删除这条操作日志吗？')) return
      try {
        await deleteOperationLog(row.id)
        this.fetchData()
      } catch (error) {
        console.error('删除操作日志失败:', error)
      }
    },
    async batchDelete() {
      const selectedIds = this.tableData.filter(item => item.selected).map(item => item.id)
      if (selectedIds.length === 0) {
        alert('请选择要删除的日志')
        return
      }
      if (!confirm(`确定要删除选中的 ${selectedIds.length} 条操作日志吗？`)) return
      try {
        await batchDeleteOperationLogs({ ids: selectedIds })
        this.fetchData()
      } catch (error) {
        console.error('批量删除操作日志失败:', error)
      }
    },
    exportLogs() {
      const selected = this.tableData.filter(r => r.selected)
      if (!selected.length) {
        alert('请选择要导出的数据')
        return
      }
      const rows = selected.map(r => ({
        '日志编号': r.logNo || r.id || '',
        '员工账号': r.account || '',
        '姓名': r.name || '',
        '操作模块': r.module || '',
        '操作内容': r.content || '',
        '操作时间': r.time || ''
      }))
      const ws = XLSX.utils.json_to_sheet(rows)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '操作日志')
      const date = new Date().toISOString().slice(0, 10)
      XLSX.writeFile(wb, `操作日志_导出_${date}.xlsx`)
      alert(`已导出选中的 ${selected.length} 条记录`)
    },
    toggleSelectAll() { 
      this.tableData.forEach(r => { r.selected = this.selectAll }) 
    },
    updateSelectAll() { 
      this.selectAll = this.tableData.length > 0 && this.tableData.every(r => r.selected) 
    },
    prevPage() { 
      if (this.currentPage > 1) {
        this.currentPage--
        this.fetchData()
      }
    },
    nextPage() { 
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.fetchData()
      }
    },
    goToPage(p) { 
      if (p !== this.currentPage) {
        this.currentPage = p
        this.fetchData()
      }
    },
    onPageSizeChange() {
      this.currentPage = 1
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.operation-logs { padding: 20px; background: #f5f7fa; }
.controls-section { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 20px; background: #fff; border-radius: 8px; margin-bottom: 16px; }
.filters { display: flex; gap: 16px; align-items: center; }
.filter-item { display: flex; gap: 8px; align-items: center; }
.filter-item input { padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; width: 220px; }
.actions { display: flex; gap: 10px; }
.btn-primary { background: #409eff; color: #fff; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; }
.btn-secondary { background: #fff; color: #606266; border: 1px solid #dcdfe6; padding: 8px 16px; border-radius: 4px; cursor: pointer; }
.table-section { background: #fff; border-radius: 8px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; }
th { background: #f8f9fa; }
.link-style { color: #409eff; cursor: pointer; }
.footer-section { display: flex; justify-content: space-between; align-items: center; margin-top: 16px; background: #fff; padding: 10px 20px; border-radius: 8px; }
.footer-left { display: flex; gap: 8px; align-items: center; }
.pagination { display: flex; gap: 8px; align-items: center; }
.pagination button { padding: 6px 12px; border: 1px solid #dcdfe6; background: #fff; border-radius: 4px; cursor: pointer; }
.pagination button.active { background: #409eff; color: #fff; border-color: #409eff; }
.pagination select { padding: 6px; border: 1px solid #dcdfe6; border-radius: 4px; }
</style>


